/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gray.swing.field;

import gray.Field;
import snippet.Snipet;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;

/**
 *
 * @author martin
 */
public class RadioField <E extends Enum<E>> extends JScrollPane implements Field<Enum<E>,Container>, ActionListener {
    private final ButtonGroup _group;    
    private final Class<E> _enumData;
    
    private RadioField(final Snipet lang,final String title, Class<E> enumData, final Character[] key){
        super();
        setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        JPanel panel = new JPanel(new GridLayout(0,1));
        setViewportView(panel);

        _enumData = enumData;
        _group = new ButtonGroup();
        JLabel lbl = new JLabel();
        lbl.setText(title);
        panel.add(lbl);
        int key_i=0;
        for (Enum<E> enumVal: enumData.getEnumConstants()) {
            JRadioButton tmp = new JRadioButton(enumVal.toString());
            tmp.setActionCommand(enumVal.toString());
            _group.add(tmp);
            panel.add(tmp);
            tmp.setMnemonic(key[key_i++]);

            tmp.setSelected(true);
            
        }
        lbl.setLabelFor(this);

    }

    public static <E extends Enum<E>> Field<Enum<E>,Container> factory(final Snipet lang,final String title, Class<E> enumData, final Character[] key){
        return new RadioField(lang, title, enumData, key);
    }
    
    @Override
    public void actionPerformed(ActionEvent arg0) {
    }

    @Override
    public Enum<E> input() {
        String name = _group.getSelection().getActionCommand();
        for (Enum<E> enumVal: _enumData.getEnumConstants()) {
            if (enumVal.toString().equals(name))
                return enumVal;
        }
        return null;
    }
    
    @Override
    public Container container() {
        return this;
    }
    
    @Override
    public Boolean ready() {
        return input()!=null;
    }
}
